package com.zbb.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zbb.user.mapper.UserMapper;
import com.zbb.user.model.dto.UserLoginDto;
import com.zbb.user.model.po.User;
import com.zbb.user.model.po.UserExt;
import com.zbb.user.service.AuthService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
* @description 账号密码认证
* @author Mr.M
* @date 2022/9/29 12:12
* @version 1.0
*/
@Service("password_authservice")
public class PasswordAuthServiceImpl implements AuthService {
@Autowired
UserMapper userMapper;
@Autowired
PasswordEncoder passwordEncoder;
@Override
public UserExt execute(UserLoginDto userLoginDto) {
 //账号
 String username = userLoginDto.getStudentId();
 User user = userMapper.selectOne(new QueryWrapper<User>()
         .eq("student_id",username)
         .or().eq("phone_no", username));
if(user==null){
 //返回空表示用户不存在
 throw new RuntimeException("账号不存在");
 }
 UserExt UserExt = new UserExt();
 BeanUtils.copyProperties(user,UserExt);
 //校验密码
 //取出数据库存储的正确密码
 String passwordDb =user.getPassword();
 String passwordForm = userLoginDto.getPassword();
 boolean matches = passwordEncoder.matches(passwordForm, 
passwordDb);
 if(!matches){
 throw new RuntimeException("账号或密码错误");
 }
 LocalDateTime time = LocalDateTime.now();
 user.setLoginTime(time);
 userMapper.updateById(user);
 return UserExt;
}


}